package com.wiseMen.wechat.user;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.user.Tag;
import org.sword.wechat4j.user.UserManager;

import com.ibm.icu.util.Calendar;
import com.wiseMen.core.dao.EntityDao;

/**
 * 用户标签管理
 * @author 吴人龙
 */
@Service("wechat_usertagservice")
public class WechatUserTagService {

	@Autowired
    private EntityDao entityDao;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 创建标签
	 * @param tagName 标签名
	 * @throws WeChatException 
	 */
	public void createTag(String tagName) throws WeChatException{
		UserManager m = new UserManager();
		Tag tag = m.createTag(tagName);
		WechatUserTagEntity entity = new WechatUserTagEntity(tag);
		this.save(entity);
	}
	
	/**
	 * 更新标签
	 * @param tagName
	 * @throws WeChatException
	 */
	public void updateTag(int tagId,String tagName) throws WeChatException{
		UserManager m = new UserManager();
		m.updateTag(tagId, tagName);
		WechatUserTagEntity entity = new WechatUserTagEntity();
		entity.setId(tagId+"");
		entity.setName(tagName);
		this.save(entity);
	}
	
	/**
	 * 删除标签
	 * @param tagId
	 * @throws WeChatException 
	 */
	public void deleteTag(int tagId) throws WeChatException{
		UserManager m = new UserManager();
		m.deleteTag(tagId);
		this.entityDao.deleteById(WechatUserTagEntity.class, tagId+"");
	}
	
	/**
	 * 批量删除
	 * @param tagId
	 * @throws WeChatException
	 */
	public void deleteTags(int[] tagId) throws WeChatException{
		for(int id : tagId){
			this.deleteTag(id);
		}
	}
	
	/**
	 * 同步所有标签
	 */
	public void syncAllTags(){
		UserManager m = new UserManager();
		List<Tag> tags = m.getTags();
		this.setAllInvalid();
		for(Tag tag : tags){
			WechatUserTagEntity entity = new WechatUserTagEntity(tag);
			this.save(entity);
		}
	}
	
	/**
	 * 判断是否已存在
	 * @param id
	 * @return boolean true:已存在  false:不存在
	 */
	private boolean isExists(String id){
		int count = this.jdbcTemplate.queryForObject("SELECT COUNT(*) WC_TAG WHERE ID=?", new String[]{id}, int.class);
		return count>0;
	}
	
	/**
	 * 保存/更新
	 * @param entity
	 */
	private void save(WechatUserTagEntity entity){
		if(StringUtils.isNotBlank(entity.getId())){
			entity.setSyncTime(Calendar.getInstance().getTime());
			entity.setInvalid(1);
			if(isExists(entity.getId())){
				this.entityDao.saveSelective(entity);
			}else{
				this.entityDao.insert(entity);
			}
		}
	}
	
	/**
	 * 更新所有标签状态为失效
	 */
	private void setAllInvalid(){
		this.jdbcTemplate.update("UPDATE WC_TAG SET INVALID=0");
	}
}
